package com.fire.user.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fire.user.constants.ErrorCodeConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fire.core.base.controller.BaseController;
import com.fire.core.service.ITMitErrorCodeService;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.BlogUtil;
import com.fire.user.model.LoginOutResp;
import com.fire.user.model.User;
import com.fire.user.model.UserReq;
import com.fire.user.service.IUserService;

/**
 * 控制器
 *
 * @author Aspire
 * @Date 2018-04-16 16:35:22
 */
@Controller
public class UserController extends BaseController {
	private  static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private String prefix = "/mit/user/";

    @Autowired
    private IUserService userService;
    @Autowired
    private ITMitErrorCodeService iTMitErrorCodeService;
    /**
     * 注册功能获取验证码
     * @param json
     * @return
     */
    @RequestMapping(value = "/verifyode",method = RequestMethod.POST)
	@ResponseBody
    public Map<String, Object> sendVerifyode(@RequestBody String json ){
		Map<String, Object> resultMap = new HashMap<>();
		UserReq userReq=JSON.parseObject(json, UserReq.class);
		if (!isPhone(userReq.getPhone())){
            LOGGER.error("UserController.sendVerifyode().error  错误为：无效的手机号码");
            resultMap.put("status","2066");
            resultMap.put("message", "无效的手机号码");
            resultMap.put("tips", "无效的手机号码");
            return  resultMap ;
        }
		try {
			resultMap = userService.getVerifyode(userReq.getPhone(),null);
		} catch ( Exception e) {
			LOGGER.error("UserController.sendVerifyode().error  错误为：",e);
		}
        return  resultMap ;
    }

	/**
	 * * 用户注册
	 * @param json（users 用户、code 验证码、type 登录方式）
	 * @return
	 */
	@RequestMapping(value= "/register", method = RequestMethod.POST)
    @ResponseBody
    public  Map<String, Object> register(@RequestBody String json ){
        Map<String,Object> resultMap=new HashMap<>(10);
		UserReq userReq=JSON.parseObject(json, UserReq.class);
		User users=new User();
		users.setChannelid(userReq.getChannelid());
		users.setPhone(userReq.getPhone());
		users.setResourcetype(userReq.getSourcetype());
		users.setResourceid(userReq.getSourceid());
        try {
            if(!("1").equals(userReq.getType())){
                //验证短信验证码是否存在或是过期
                if (StringUtils.isNoneEmpty(userReq.getCode())){
					resultMap=userService.getVerifyode(userReq.getPhone(),userReq.getCode());
					String status=resultMap.get("status").toString();
					if(!"0".equals(status)){
						return resultMap;
					}
                }else{
					//设置密码
					users.setPasswd(userReq.getCode());
				}
            }
            	LOGGER.info("=======USER----add ==============");
				resultMap = userService.addUser(users);
        } catch ( Exception e){
			resultMap.put("status", "1");
			resultMap.put("message", "用户已存在");
			resultMap.put("tips", "用户已存在");
        	LOGGER.error("UserController.register().error  错误为：",e);

        }
        return  resultMap;
    }
    
    @RequestMapping(value="/login",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(@RequestBody String json){
		Map<String,Object> resultMap=new HashMap<>(10);
		UserReq userReq=JSON.parseObject(json, UserReq.class);
		User users=new User();
		users.setChannelid(userReq.getChannleid());
		users.setPhone(userReq.getPhone());
		users.setResourcetype(userReq.getSourcetype());
		users.setResourceid(userReq.getSourceid());
    	   try {
			   if(!("1").equals(userReq.getType())){
				   //验证短信验证码是否存在或是过期
				   if (StringUtils.isNoneEmpty(userReq.getCode())){
					   resultMap=userService.getVerifyode(userReq.getPhone(),userReq.getCode());
					   String status=resultMap.get("status").toString();
						if(!"0".equals(status)){
							return resultMap;
						}
				   }else{
					   //设置密码
					   users.setPasswd(userReq.getCode());
				   }
			   }
			   resultMap = userService.loginUser(users);
		} catch (Exception e) {
			   LOGGER.error("UserController.login().error  错误为：",e);
			   resultMap.put("status", "2015");
			   resultMap.put("message", "登录异常");
			   resultMap.put("tips", "登录异常");
		}
    	
    	return  resultMap;
    }


    /**
	 * 获取用户个人信息
	 * @param  userid
     * @return
	 */
	@RequestMapping(value = "/getuserinfo", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult getuserInfo(@RequestBody String json) {
		LOGGER.info(json);
		AjaxResult ajaxResult = new AjaxResult();
		try {
			ajaxResult = userService.getuserInfo(json);
        }catch (Exception e) {
        	LOGGER.error("UserController.getuserInfo().error  错误为：",e);
        	ajaxResult.setTips("系统内部错误");
    		ajaxResult.setMessage("系统内部错误");
    		ajaxResult.setStatus(ErrorCodeConstants.INTERNAL_ERROR);
		}
		String tips = iTMitErrorCodeService.getTips(ajaxResult.getStatus()); 
    	if(StringUtils.isNotBlank(tips)) {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+tips);
    	}else {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+ajaxResult.getTips());
    	}
		return ajaxResult;
	}
    

	/**
	 * 个人用户设置
	 * @param token avatar
     * @return
	 */
	@RequestMapping(value = "/usersetting", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult usersetting(@RequestBody String json) {
		LOGGER.info(json);
		AjaxResult ajaxResult = new AjaxResult();
		try {
			ajaxResult = userService.usersetting(json);
		}catch (Exception e) {
        	LOGGER.error("UserController.usersetting().error  错误为：",e);
        	ajaxResult.setTips("系统内部错误");
    		ajaxResult.setMessage("系统内部错误");
    		ajaxResult.setStatus(ErrorCodeConstants.INTERNAL_ERROR);
		}
		String tips = iTMitErrorCodeService.getTips(ajaxResult.getStatus()); 
    	if(StringUtils.isNotBlank(tips)) {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+tips);
    	}else {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+ajaxResult.getTips());
    	}
		return ajaxResult;
	}

	/**
	 * 更改密码/忘记密码
	 * @param  json
     * @return
	 */
	@RequestMapping(value = "/chgpwd", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult changePassword(@RequestBody String json) {
		LOGGER.info(json);
		AjaxResult ajaxResult = new AjaxResult();
		try {
			ajaxResult = userService.changePassword(json);
		}catch (Exception e) {
        	LOGGER.error("UserController.changePassword().error  错误为：",e);
        	ajaxResult.setTips("系统内部错误");
    		ajaxResult.setMessage("系统内部错误");
    		ajaxResult.setStatus(ErrorCodeConstants.INTERNAL_ERROR);
		}
		String tips = iTMitErrorCodeService.getTips(ajaxResult.getStatus()); 
    	if(StringUtils.isNotBlank(tips)) {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+tips);
    	}else {
    		ajaxResult.setTips("["+ajaxResult.getStatus()+"]"+ajaxResult.getTips());
    	}
		return ajaxResult;
	}
	
	
	 /**
     * 用户退出
     * @param req
     * @param resp
     * */
    @RequestMapping("/logout")
    @ResponseBody
    public LoginOutResp logout(HttpServletRequest req, HttpServletResponse resp,@RequestBody String json){
    	LOGGER.info("用户开始退出。。。。。");
    	resp.setCharacterEncoding("utf-8");
    	LoginOutResp ajaxResult=null;
    	Map<String,Object> param = JSONObject.parseObject(json, Map.class);
    	try {
    		ajaxResult=userService.logout(json);
		} catch (Exception e) {
			LOGGER.error("UserController.logout().error  错误为：",e);
		}
    	BlogUtil.inlog(json, String.valueOf(param.get("token")), "mit/user/logout", "logout", "resp");
    	return ajaxResult;
    	
    }
	
   

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return prefix + "user.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/user_add")
    public String userAdd() {
        return prefix + "user_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/user_update/{userId}")
    public String userUpdate(@PathVariable Integer userId, Model model) {
        User user = userService.selectById(userId);
        model.addAttribute("item",user);
      /*  LogObjectHolder.me().set(user);*/
        return prefix + "user_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return userService.selectList(null);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(User user) {
        userService.insert(user);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer userId) {
        userService.deleteById(userId);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(User user) {
        userService.updateById(user);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{userId}")
    @ResponseBody
    public Object detail(@PathVariable("userId") Integer userId) {
        return userService.selectById(userId);
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }


}

